package servlet;

import core.ServletBase;
import weka.ClassifierHelpper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by taohj on 2014/12/19.
 */
@WebServlet("/classifyServlet")
public class ClassifyServlet extends ServletBase {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        String action = req.getParameter("action");


        if ("input".equals(action)) {
            req.getRequestDispatcher("WEB-INF/page/tabs/classify/classify.jsp").forward(req, resp);
        } else if ("start".equals(action)) {
            start(req, resp);
        } else if ("treevisualize".equals(action)) {
            req.getRequestDispatcher("WEB-INF/page/tabs/classify/treevisualize.jsp").forward(req, resp);
        }
        else {
            throw new ServletException("未找到参数action的对应项");
        }

    }


    private void start(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String filepath = super.getCurrentFilePath(req);
        String classifier = req.getParameter("classifyer");
        String option = req.getParameter("option");
        try {
            ClassifierHelpper helpper = new ClassifierHelpper(filepath, classifier, option);

            String result = helpper.start().toString();

            result = result.replaceAll(" ", "\u007F ");

            print(resp, result);
        } catch (Exception e) {
            e.printStackTrace();
            print(resp, e.getLocalizedMessage());
        }
    }
}
